package com.cv.framework.jackson.config;

import cn.hutool.core.collection.CollUtil;
import com.cv.framework.common.utils.json.JsonUtil;
import com.cv.framework.jackson.core.databind.LocalDateTimeDeserializer;
import com.cv.framework.jackson.core.databind.LocalDateTimeSerializer;
import com.cv.framework.jackson.core.databind.NumberSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * Jackson 自动配置类
 *
 * @author Charles_XDXD
 */
@AutoConfiguration
@Slf4j
public class CvJacksonAutoConfiguration {

    @Bean
    @SuppressWarnings("InstantiationOfUtilityClass")
    public JsonUtil jsonUtils(List<ObjectMapper> objectMappers) {
        log.info("[init][正在初始化 JsonUtils]");
        SimpleModule simpleModule = new SimpleModule();

        simpleModule
                .addSerializer(Long.class, NumberSerializer.INSTANCE)
                .addSerializer(Long.TYPE, NumberSerializer.INSTANCE)
                .addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE)
                .addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE)
                .addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE)
                .addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE)
                .addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE)
                .addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);

        objectMappers.forEach(objectMapper -> objectMapper.registerModule(simpleModule));

        JsonUtil.init(CollUtil.getFirst(objectMappers));
        log.info("[init][初始化 JsonUtils 完毕]");
        return new JsonUtil();
    }

}
